<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 商品属性表
 *
 * @icon fa fa-circle-o
 */
class Goodsattribute extends Backend
{
 
	protected $relationSearch = true;
	
    /**
     * GoodsAttribute模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('GoodsAttribute');
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("mustList", $this->model->getMustList());
        $this->view->assign("searchShowList", $this->model->getSearchShowList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax())
		{
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('pkey_name'))
			{
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,true);
			
			
			$total = $this->model
				->with('category')
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with('category')
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				if ($this->dataLimit && $this->dataLimitFieldAutoFill)
				{
					$params[$this->dataLimitField] = $this->auth->id;
				}
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					$result = $this->model->allowField(true)->save($params);
					if ($result !== false)
					{
						$this->success();
					}
					else
					{
						$this->error($this->model->getError());
					}
				}
				catch (\think\exception\PDOException $e)
				{
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$cateModel = new \app\common\model\GoodsCategory();
		return $this->view->fetch('add',[
			'categorys' => $cateModel->getTreeCategory(),
		]);
	}
	
	
	/**
	 * 编辑
	 */
	public function edit($ids = NULL)
	{
		$row = $this->model->get($ids);
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds))
		{
			if (!in_array($row[$this->dataLimitField], $adminIds))
			{
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					
					
					$result = $row->allowField(true)->save($params);
					if ($result !== false)
					{
						$this->success();
					}
					else
					{
						$this->error($row->getError());
					}
				}
				catch (\think\exception\PDOException $e)
				{
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		$cateModel = new \app\common\model\GoodsCategory();
		return $this->view->fetch('edit',[
			'categorys' => $cateModel->getTreeCategory()
		]);
	}
	
	
	/**
	 * 获取分类属性
	 */
	public function getCategoryAttr(){
		$cid = input('post.cid');
		$goodsId = input('post.goods_id');
		
		$rows = [];
		if($goodsId && $goodsId > 0){
			$rows = Db::name('goodsAttrValue')->where(['goods_id' => $goodsId])->column('value', 'attr_id');
		}
		$attrs = $this->model->where(['category_id' => $cid])->select();
		if($attrs){
			foreach($attrs as $key => $attr){
				$selectVal = [];
				if(in_array($attr['id'], array_keys($rows))){
					$selectVal = explode(' ',$rows[$attr['id']]);
				}
				
				$v = '';
				if($attr['type'] != 3){
					$values = explode(';', str_replace('，',',',$attr['values']));
					foreach($values as $value){
						if(in_array($value, $selectVal)){
							$v[] = [
								'value' => $value,
								'checked' => true
							];
						} else {
							$v[] = [
								'value' => $value,
								'checked' => false
							];
						}
					}
				} else {
					if(in_array($attr['id'], array_keys($rows))){
						$v = $rows[$attr['id']];
					}
				}
				$attrs[$key]['values'] = $v;
				
			}
		}
		$this->success('查询成功','',$attrs);
	}
}
